package com.hyl.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Description 拦截器
 * @Author hyl
 * @Date 2023/5/18 11:48
 **/
//拦截器
public class LoginInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//获取请求的URL
		String requestURI = request.getRequestURI();
		HttpSession session = request.getSession();
		System.out.println("链接:" + requestURI + "进入拦截器");
		if (request.getSession().getAttribute("userSession") == null) { //表示未登录就想进入系统
			//直接重定向到登录界面
			String serverPath = request.getScheme() + "://" + request.getServerName() + ":"
					+ request.getServerPort() + request.getContextPath() + "/login.jsp";
			response.sendRedirect(serverPath);
			return false;
		} else {
			//登陆成功，不拦截
			return true;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		System.out.println("跳转后拦截");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		System.out.println("渲染后拦截");
	}
}
